import { loadPoint, loadPointIcon } from '@/hooks/earth/utils'
import { v1 } from 'uuid'
import PolylineTrailMaterialProperty from './customMaterial.js'

import { explotEffect } from './explotEffect.js'

import dayjs from 'dayjs'
import { useEarthStore } from '@/stores/earth'
import _ from 'lodash'
class Move {
  constructor() {
    this.viewer = viewer
    // 添加相关图层
    this._layer = new Cesium.CustomDataSource('movelayer')
    viewer.dataSources.add(this._layer)
    this.earthStore = useEarthStore()
  }


  stopmove() {
    this._layer.entities.removeAll()
    viewer.clock.multiplier = 1
    viewer.clock.shouldAnimate = false;

  }

  startmove(data, path) {
    // 生成起始时间
    this.start = Cesium.JulianDate.fromDate(new Date(data.data[0].time))
    this.stop = Cesium.JulianDate.fromDate(
      new Date(data.data[data.data.length - 1].time),
    )
    viewer.clock.shouldAnimate = true;
    // 设置始时钟始时间
    viewer.clock.startTime = this.start
    // 设置时钟当前时间
    viewer.clock.currentTime = this.start
    // 设置始终停止时间
    viewer.clock.stopTime = this.stop
    // 时间速率，数字越大时间过的越快
    viewer.clock.multiplier = 1
    // 时间轴
    viewer.timeline.zoomTo(this.start, this.stop)
    // 循环执行,即为2，到达终止时间，重新从起点时间开始
    viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP

    // 添加实体对象
    let modelPath = ''

    if (data.type == 'man') {
      modelPath = 'models/walk.gltf'
    }
    if (data.type == 'drone') {
      modelPath = 'models/mqwrj.glb'
    }

    let posproperty = this.computeTrack(data.data)
    let orientationposproperty = new Cesium.VelocityOrientationProperty(posproperty)
    // posproperty.setInterpolationOptions({
    //   interpolationDegree: 2,
    //   interpolationAlgorithm: Cesium.HermitePolynomialApproximation
    // })

    let respos = []

    data.data.map((item) => {
      respos.push(
        Cesium.Cartesian3.fromDegrees(
          item.longitude,
          item.latitude,
          item.height,
        ),
      )
      // this._layer.entities.add(
      //   loadPoint([item.longitude, item.latitude], item.time),
      // )
      loadPointIcon({ icon: '/assets/3d/t/time.png', loc: [item.longitude, item.latitude], name: item.time }, 'linePoi1.png').then(res => {

        this._layer.entities.add(
          res
        )
      })

    })

    viewer.scene.globe.enableLighting = false
    viewer.shadows = false
    earth.effect.forceSunPos.enabled = true



    let _this = this

    let entityconfig = {
      name: modelPath,
      // 和时间轴关联
      show: true,
      // availability: new Cesium.TimeIntervalCollection([
      //   new Cesium.TimeInterval({
      //     start: this.start,
      //     stop: this.stop,
      //   }),
      // ]),
      // position: posproperty,
      position: new Cesium.CallbackProperty((time, result) => {
        let result1
        var curtime = viewer.clock.currentTime;
        // if (condition) {

        // }
        var pos = posproperty.getValue(time, result1);
        _.throttle(function () {
          console.log(dayjs(time.toString()).format('YYYY-MM-DD HH:mm:ss'));
        },1000)()
        if (_.has(_this.earthStore.timeline_arr_kv, dayjs(time.toString()).format('YYYY-MM-DD HH:mm:ss'))) {

          let item = _this.earthStore.timeline_arr_kv[dayjs(time.toString()).format('YYYY-MM-DD HH:mm:ss')]
          // console.log(item);
          // this.debounceDrop(pos,item )
          // this.debounceExplosion([item['longitude'],item['latitude']])
          if (item.keywords.indexOf('摧毁') !== -1) {
            this.debounceExplosion([item['longitude'],item['latitude']])
          }
          if (item.keywords.indexOf('投弹') !== -1) {
            this.debounceDrop(pos,item )
          }

        }
        let c = Cesium.Ellipsoid.WGS84.cartesianToCartographic(pos)
        return Cesium.Cartesian3.fromDegrees(Cesium.Math.toDegrees(c.longitude), Cesium.Math.toDegrees(c.latitude), 0)
      }, false),
      // 根据所提供的速度计算模型的朝向
      // orientation: new Cesium.VelocityOrientationProperty(posproperty),
      orientation: new Cesium.CallbackProperty((time, result) => {

        let result1;
        // var curtime = viewer.clock.currentTime;
        // if (condition) {

        // }
        // var pos = posproperty.getValue(time, result1);

        // console.log(orientationposproperty.getValue(time, result1));

        return orientationposproperty.getValue(time, result1)
      }, false),
      // 模型数据
      polyline: {
        positions: respos,
        width: 7,
        // material: Cesium.Color.BLUE.withAlpha(0.5),
        material: new PolylineTrailMaterialProperty(Cesium.Color.BLUE,
          2000, "/assets/3d/t/DotTransparent.png", 1.0, 1.0),
        clampToGround: true,
        // ...options.options
      },
      // path: {
      //     resolution: 1,
      //     width: 7,
      //     material: new Cesium.PolylineGlowMaterialProperty({
      //     glowPower: 0.1,
      //     color: Cesium.Color.YELLOW,
      //   }),
      //   // material: Cesium.Color.BLUE.withAlpha(0.5),
      //   // material: new PolylineTrailMaterialProperty(Cesium.Color.BLUE,
      //   // 2000,"/assets/3d/t/DotTransparent.png",1.0,1.0),
      //   // clampToGround: true,
      //   // ...options.options
      // },
    }

    if (path == '') {
      var imgaes = `/assets/v2/icon_bh.png`
      entityconfig.billboard = {
        //图标
        image: imgaes,
        width: 25,
        // pixelOffset: new Cesium.Cartesian2(0, -50), //偏移量
        pixelOffset: new Cesium.Cartesian2(0, -25), //偏移量
        height: 50,
        // translucencyByDistance: new Cesium.NearFarScalar(10000, 1.0, 10000, 0.0)
      }
    } else {
      entityconfig.model = {
        id: v1(),
        minimumPixelSize: 128,
        maximumScale: 200000,
        uri: path,
        scale: 1,
      }
    }

    this._layer.entities.add(entityconfig)
    // 添加爆炸效果

    // let explot = new explotEffect(viewer,[data.data[0].longitude, data.data[0].latitude])

    // return

  }

  handleExplosion(pos) {
    console.log(pos);
    var staticPosition = Cesium.Cartesian3.fromDegrees(...pos, 5000);
    var entity44 = viewer.entities.add({
      position: staticPosition
    })

    function computeModelMatrix(entity, time) {
      var position = Cesium.Property.getValueOrUndefined(entity.position);
      let modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(position);
      return modelMatrix;
    }

    function computeEmitterModelMatrix() {
      let hpr = Cesium.HeadingPitchRoll.fromDegrees(0, 0, 0);
      let trs = new Cesium.TranslationRotationScale();
      trs.translation = Cesium.Cartesian3.fromElements(2.5, 4, 1);
      trs.rotation = Cesium.Quaternion.fromHeadingPitchRoll(hpr);
      let result = Cesium.Matrix4.fromTranslationRotationScale(trs);
      return result
    }

    let explot = viewer.scene.primitives.add(new Cesium.ParticleSystem({
      // image : '/assets/3d/t/smoke.png',
      image: '/img/explosion.png',
      startColor: Cesium.Color.RED.withAlpha(0.7),
      endColor: Cesium.Color.YELLOW.withAlpha(0.3),
      startScale: 0,
      endScale: 5,
      //设定粒子寿命可能持续时间的最小限值(以秒为单位)，在此限值之上将随机选择粒子的实际寿命。
      minimumParticleLife: 1,
      maximumParticleLife: 1,
      minimumSpeed: 1,
      maximumSpeed: 4,
      imageSize: new Cesium.Cartesian2(25, 25),
      // Particles per second.
      emissionRate: 4,
      particleSize: 4,
      lifetime: 160.0,
      //cesium内置的发射器，圆形发射器，因此参数是一个半径值
      //还有锥形发射器，new Cesium.ConeEmitter(Cesium.Math.toRadians(45.0))
      //长方形发射器，new Cesium.BoxEmitter(new Cesium.Cartesian3(1.0, 1.0, 1.0))
      //半球发射器，new Cesium.SphereEmitter(0.5)
      emitter: new Cesium.CircleEmitter(5.0),
      //将粒子系统从模型转换为世界坐标的4x4变换矩阵
      modelMatrix: computeModelMatrix(entity44),
      //在粒子系统局部坐标系中变换粒子系统发射器的4x4变换矩阵
      emitterModelMatrix: computeEmitterModelMatrix()
    }))

    setTimeout(() => {
      viewer.scene.primitives.remove(explot)
    }, 6000);
  }

  debounceExplosion = _.debounce(this.handleExplosion, 500, {
    leading: true, // 延长开始后调用
    trailing: false, // 延长结束前调用
  })



  handleDrop(pos, item) {
    // 添加投弹效果(弹跳)
    let dropentity = {
      position: pos,
      billboard: {
        image: '/img/rocket.png',
        width: 62,
        pixelOffset: new Cesium.Cartesian2(0, -50), //偏移量
        height: 100,
      }
    }
    let drope = this._layer.entities.add(dropentity)
    this.openBounce(drope, [item.longitude, item.latitude])
    setTimeout(() => {
      this._layer.entities.remove(drope)
    }, 3000);

  }

  debounceDrop = _.debounce(this.handleDrop, 500, {
    leading: true, // 延长开始后调用
    trailing: false, // 延长结束前调用
  })

  openBounce(entity, position) {
    // 跳动最大高度
    const maxHeight = 100;
    // 跳动速率
    const step = 2;
    // 过程高度
    let height = 0;
    // 跳动反转标记
    let statusForBounce = true;
    entity._defaultPosition = entity._position;
    // 弹跳回调
    entity.billboard.pixelOffset = new Cesium.CallbackProperty(function (time, result) {
      if (statusForBounce) {
        height = height - step;
        if (height <= 0) {
          statusForBounce = false;
        }
      } else {
        height = height + step;
        if (height >= maxHeight) {
          statusForBounce = true;
        }
      }
      return new Cesium.Cartesian2(0, -height - 50);
    }, false);
  }

  /**
   * 计算飞行
   * @param source 数据坐标
   * @returns {SampledPositionProperty|*}
   */
  computeTrack(source) {
    // 取样位置 相当于一个集合
    let property = new Cesium.SampledPositionProperty()
    for (let i = 0; i < source.length; i++) {
      let time = Cesium.JulianDate.fromDate(new Date(source[i].time))
      let position = Cesium.Cartesian3.fromDegrees(
        source[i].longitude,
        source[i].latitude,
        source[i].height,
      )
      // 添加位置，和时间对应
      property.addSample(time, position)
    }
    return property
  }
}

// export {move}
export default Move
